#pragma once
#include <bondlib/BondInfo.h>
#include <core/strings/pinyin_search.h>
#include <widgets/KeySearchWidget.h>

#include <map>
#include <mutex>
#include <vector>

#include "Detail/BondDetailData.h"

class BondDetailData;
// 债券搜索标志位
enum SearchFlag {
  BSF_EXCLUDE_ADDISSUEBOND = 0x00000001,  // 排除增续发债券
  BSF_EXCLUDE_DATEEXPIRED = 0x00000002,   // 排除过期债券
  BSF_SELECT_FIRST = 0x00000004,          // 选择第一个,废弃,不再使用
  BSF_USE_TITLELIST = 0x00000008,         // 使用BondSearchForTitleListBox
  BSF_SELECT_NOSELECT = 0x00000010,       // 不选第一个(默认)
  BSF_RESTRIC_ABS = 0x00000020,           // 仅包含ABS券
  BSF_SELECT_ABSBOND_CIB = 0x00000040,    // 仅包含银行间ABS券
  BSF_SEARCHSPIRIT = 0x00000080,          // 按键精灵 全局搜索
  BSF_ENGLISHFLAG = 0x00000100,           // 英文版
  BSF_ATTVALID_BONDFLAG = 0x00000200,     // 我的关注有效债券
  BSF_RESTRIC_FIX_RATE = 0x00000400,      // 仅包含固息债
  BSF_RESTRIC_INTEREST = 0x00000800       // 仅包含利率债
};

class MainSearchEngine : public IKeySearchEngine,
                         qb::base::ISpellSearchListener {
 public:
  virtual void search(int serialNum, const QString& key) override;
  virtual void setUserData(int userdata) override;
  virtual void setResultCallback(
      std::function<void(int, QJsonArray)> fun) override;
  virtual void onResultSelected(const QString& key) override;

  virtual int GetResultCount() const override;
  virtual bool OnResult(const int* ids, int ncount, const char* key,
                        int len) override;

  void setFlag(SearchFlag flags) { m_flag = flags; }

 protected:
  virtual void doSearch(int serialNum, const QString& key);
  const std::vector<int>& SortResults(const int* ids, int& ncount);
  void matchIssuers(const char* pText, int number, QJsonArray& results);
  bool isMatch(const CBondInfo& info, const char* text, int len,
               bool bIsAllNumber);
  bool IsStringNumber(const char* key);

 protected:
  std::function<void(int, QJsonArray)> m_fun = nullptr;
  int m_resCount = 0;
  std::map<QString, int> m_searchHis;
  volatile int m_curSearchSerialNum = 0;
  std::mutex m_lock;
  std::vector<int> m_vecSortedIds;
  SearchFlag m_flag;
};

class BondInterSearchEngine : public MainSearchEngine {
 public:
  void setBondData(QSharedPointer<DetailData> data);
  void onResultSelected(const QString& key) override;

 private:
  QSharedPointer<DetailData> m_data = nullptr;
};
